package com.example.communist_app_api.service.impl;

import com.example.communist_app_api.db.dao.OrganizationDao;
import com.example.communist_app_api.db.dao.UserOrganizationDao;
import com.example.communist_app_api.db.dto.OrganizationDTO;
import com.example.communist_app_api.db.pojoDto.Organization;
import com.example.communist_app_api.db.pojoDto.OrganizationalStructureDTO;
import com.example.communist_app_api.db.pojoDto.Role;
import com.example.communist_app_api.db.pojoDto.User;
import com.example.communist_app_api.enums.OrganizationLevelEnum;
import com.example.communist_app_api.enums.RoleNameEnum;
import com.example.communist_app_api.exception.GlobalException;
import com.example.communist_app_api.service.OrganizationService;
import com.example.communist_app_api.service.RoleService;
import com.example.communist_app_api.service.UserRoleService;
import com.example.communist_app_api.service.UserService;
import com.example.communist_app_api.util.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Brother Sheng Editor
 * @version 1.0
 * Create by 2023/2/21 16:19
 */
@Service
@Transactional
public class OrganizationServiceImpl implements OrganizationService {
    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserOrganizationDao userOrganizationDao;

    @Autowired
    private UserService userService;

    @Override
    public Integer getOrganizationIdByOrganizationName(String organizationName) {
        return organizationDao.getOrganizationIdByOrganizationName(organizationName);
    }

    @Override
    public Organization getOrganizationByOrganizationName(String organizationName) {
        return organizationDao.getOrganizationByOrganizationName(organizationName);
    }

    @Override
    public Organization getOrganizationByOrganizationId(Integer id) {
        return organizationDao.getOrganizationByOrganizationId(id);
    }

    @Override
    public List<OrganizationDTO> getAllCommunist(String organizationName) {
        return organizationDao.getAllCommunist(organizationName);
    }

    //模糊查找组织
    @Override
    public List<OrganizationDTO> findOrganizationName(String organizationName) {
        return organizationDao.findOrganizationName(organizationName);
    }

    @Override
    public Organization getParentIdIsZero() {
        return organizationDao.getParentIdIsZero();
    }

    @Override
    public Boolean createNewPartyCommittee(Organization createOrganization) {
        createOrganization.setParentId(0);
        createOrganization.setOrganizationLevel(OrganizationLevelEnum.PartyCommittee.getMessage());
        return organizationDao.createOrganization(createOrganization);
    }

    @Override
    public Boolean createGeneralPartyBranch(Organization createOrganization) {
        createOrganization.setOrganizationLevel(OrganizationLevelEnum.GeneralPartyBranch.getMessage());
        return organizationDao.createOrganization(createOrganization);
    }

    @Override
    public Boolean createPartyBranch(Organization createOrganization) {
        createOrganization.setOrganizationLevel(OrganizationLevelEnum.PartyBranch.getMessage());
        return organizationDao.createOrganization(createOrganization);
    }

    @Override
    public PageInfo<OrganizationalStructureDTO> selectAllOrganization(Organization organization, Integer pageNum, Integer pageSize, Integer userId) {
        PageHelper.startPage(pageNum,pageSize);
        //判断useId是谁?身份是管理员还总支书记（这种情况是每个人角色都只有一个的时候，不然会报错）
        List<Role> roleByUserId = userRoleService.getRoleByUserId(userId);
        if (roleByUserId.size()>1) {
            throw new GlobalException("这个用户有多重角色");
        }
        String roleName = roleService.getRoleNameByUserId(userId);
        //模糊查找
        String organizationName = organization.getOrganizationName();
        if(roleName.equals(RoleNameEnum.SystemAdministrator.getMessage())){
            //判断不为空进行系统管理员的模糊查找
            if (StringUtil.isNotEmpty(organizationName)) {
                List<OrganizationalStructureDTO> organizationalStructureDTOList = organizationDao.getOrganizationByVagueOrganizationName(organizationName);
                return new PageInfo<>(organizationalStructureDTOList,5);
            }
            //organizationName为空，查询全部
            //先查询所有党委，查询parentId = 0的所有党委
             List<OrganizationalStructureDTO> organizationalStructureDTOList = organizationDao.getParentIdIsZeroOrganization();
            organizationalStructureDTOList.stream().forEach(n->{
                //查看是否有党总支
                //parentId作为党总支的parentId
                Integer parentId = n.getId();
                List<OrganizationalStructureDTO> GeneralPartyBranchList = organizationDao.getParentIdOrganizationByParentId(parentId);
                GeneralPartyBranchList.stream().forEach(m->{
                    //查看是否有党支部
                    Integer PartyBranchParentId = m.getId();
                    List<OrganizationalStructureDTO> partyBranchBranchList = organizationDao.getParentIdOrganizationByParentId(PartyBranchParentId);
                    m.setChildrenList(partyBranchBranchList);
                });
                n.setChildrenList(GeneralPartyBranchList);
            });
            return new PageInfo<>(organizationalStructureDTOList,5);
        }else if (roleName.equals(RoleNameEnum.SecretaryOfTheGeneralBranch.getMessage())){
            //判断角色身份是党总书记，只能查看所管辖的总支
            Organization organizationByUserId = userOrganizationDao.getOrganizationByUserId(userId);
            ArrayList<OrganizationalStructureDTO> generalPartyBranchList = new ArrayList<>();
            OrganizationalStructureDTO organizationalStructureDTO = new OrganizationalStructureDTO();
            organizationalStructureDTO.setId(organizationByUserId.getId());
            organizationalStructureDTO.setParentId(organizationByUserId.getParentId());
            organizationalStructureDTO.setOrganizationLevel(organizationByUserId.getOrganizationLevel());
            organizationalStructureDTO.setAddress(organizationByUserId.getAddress());
            organizationalStructureDTO.setOrganizationName(organizationByUserId.getOrganizationName());
            organizationalStructureDTO.setTelephone(organizationByUserId.getTelephone());
            organizationalStructureDTO.setChairman(organizationByUserId.getChairman());
            organizationalStructureDTO.setCreatedTime(organizationByUserId.getCreatedTime());
            organizationalStructureDTO.setUpdatedTime(organizationByUserId.getUpdatedTime());
            organizationalStructureDTO.setIsDeleted(organizationByUserId.getIsDeleted());
            //查询党总支下面的党支部
            List<OrganizationalStructureDTO> partyBranchBranchList = organizationDao.getParentIdOrganizationByParentId(organizationByUserId.getId());
            organizationalStructureDTO.setChildrenList(partyBranchBranchList);
            generalPartyBranchList.add(organizationalStructureDTO);
            return new PageInfo<>(generalPartyBranchList,5);
        }else{
            throw new GlobalException("当前身份："+roleName+"不支持查看组织架构");
        }
    }

    /**
     *
     * @param userIdBySecretaryOfTheGeneralBranch 任命总支书记的Id
     * @param userId 操作当前Web端的用户Id
     */
    @Override
    public void assignSecretaryOfTheGeneralBranch(Integer userIdBySecretaryOfTheGeneralBranch, Integer userId,Integer organizationId) {
        //根据userId查询user用户信息
        User user = userService.getUserByUserId(userIdBySecretaryOfTheGeneralBranch);
        //根据组织Id查询组织信息
        Organization organization = organizationDao.getOrganizationByOrganizationId(organizationId);
        organization.setChairman(user.getName());
        organization.setTelephone(user.getTelephone());
        //更新组织信息
        organizationDao.updateOrganization(organization);
        //由于总支书记一开始进入的组织就是党总支，所以不用变更user_organization表

        //分配总支书记的角色
        //查询总支书记角色的Id
        Integer roleId = roleService.getRoleIdByRoleName(RoleNameEnum.SecretaryOfTheGeneralBranch.getMessage());
        Integer assignNum = userRoleService.assignRole(userIdBySecretaryOfTheGeneralBranch,roleId);
        if (assignNum  == 0) {
            throw new GlobalException("任命失败：分配角色失败");
        }
    }

    /**
     *
     * @param userIdBySelect 被选中任命党支部书记的Id
     * @param userIdByWebToken 当前Web端操作的用户Id
     */
    @Override
    public void assignBranchSecretary(Integer userIdBySelect, Integer userIdByWebToken,Integer organizationId) {
        //判断这个党支部之前是否有党支部书记，有的话需要继续更换操作，主要涉及是
        // 1.删除原先用户的有关党支部书记的权限user_role表的相关信息，把原先的党支部书记用户身份改成普通党员权限
        // 2.其次修改organization表中chairman和telephone的相关信息
        //根据organizationId查询organization的相关信息
        User user = userService.getUserByUserId(userIdBySelect);
        Organization organization = organizationDao.getOrganizationByOrganizationId(organizationId);

        //查询党支部书记角色的Id
        Integer roleId = roleService.getRoleIdByRoleName(RoleNameEnum.BranchSecretary.getMessage());
        Integer ChineseCommunistPartyMembersRoleId = roleService.getRoleIdByRoleName(RoleNameEnum.ChineseCommunistPartyMembers.getMessage());

        //根据organization中chairman查询user表中的userId，然后根据UserId删除user_role表中的信息
        //判断organization中chairman是否为空，为空说明是没有设置党支部书记
        if (StringUtil.isNotEmpty(organization.getChairman())){
            //判断不为空的情况
            int userId = userService.getUserByUserName(organization.getChairman());
            //根据userId去查找可能会出现误删的情况，存在多个角色的情况，给个userId和roleId(党支部书记的Id)
            Boolean deletedFlag = userRoleService.deleteUserRoleByUserId(userId,roleId);
            if(!deletedFlag){
                throw  new GlobalException("删除用户_角色表信息出错");
            }
            Integer insertNum =userRoleService.insertUserRole(userId,ChineseCommunistPartyMembersRoleId);
            if(insertNum != 1){
                throw  new GlobalException("新增用户_角色表信息出错");
            }
        }
        organization.setTelephone(user.getTelephone());
        organization.setChairman(user.getName());

        //更新组织信息
        Boolean updateFlag = organizationDao.updateOrganization(organization);

        if (!updateFlag){
            throw new GlobalException("更新组织失败");
        }

        //分配党支部书记的角色
        Integer assignNum = userRoleService.assignRole(userIdBySelect,roleId);
        if (assignNum  == 0) {
            throw new GlobalException("任命失败：分配角色失败");
        }

        //党支部书记，组织关系由党总支转变为党支部
        Boolean updateUserOrganization = userOrganizationDao.updateUserOrganization(userIdBySelect,organizationId);
        if (!updateUserOrganization){
            throw new GlobalException("转组织失败");
        }
    }

    @Override
    public void updateOrganizationMessage(Organization organization, Integer userIdByWebToken) {

        Boolean updateFlag = organizationDao.updateOrganization(organization);
        if (!updateFlag){
            throw new GlobalException("组织信息更新失败");
        }
    }

    /**
     *
     * @param organizationId 要被删除的组织Id
     * @param userIdByWebToken
     */
    @Override
    public void deletedPartyBranch(Integer organizationId, Integer userIdByWebToken) {
        //TODO 遗留数据问题，党支部中某个用户被删除不可见之后，is_deleted = 1，党支部人员转移后仍存在这些is_deleted=1的用户数据
        organizationDao.deleteOrganizationMessage(organizationId);
    }

    @Override
    public String getOrganizationLevelById(Integer id) {
        return organizationDao.getOrganizationLevelById(id);
    }
}
